<template>
  <!-- 聊天群 -->
  <div class="chatpanel-container">
    <!-- 群信息 -->
    <div class="group-info">
      <div class="info" @click="onQuitGroupChat">
        <i class="fa fa-angle-left fa-lgl"></i>
        <!-- <span>返回</span> -->
        <!-- <div class="group-name">{{ group.groupNick }} (群号: {{ group.groupId }})</div> -->
      </div>

      <div
        class="chat-card flexbox justify-end"
        v-if="showChatCard"
        v-hammer:tap="onChatCardClicked"
      >
        <div class="icon">
          <img :src="chatCard.leftIcon" alt />
        </div>
        <!-- <div class="info">
          <div class="title">{{ chatCard.title }}</div>
          <div class="content">{{ chatCard.content }}</div>
        </div>-->
      </div>

      <div class="setting" @click="onSetting">
        <img src="@/assets/icons/setting.svg" alt class="svg-icon" />
      </div>
    </div>

    <!-- 聊天置顶卡片 -->
    <!-- <div class="top-fixed-card" v-if="showChatCard">
      <chat-card :card="chatCard" v-hammer:tap="onChatCardClicked" />
    </div>-->

    <!-- 聊天内容 -->
    <div class="chatpanel" :style="panelStyle">
      <!-- :style="listStyle" -->
      <!-- :class="{'show-tool': showTool}" -->
      <div class="group-list-wrapper" v-hammer:tap="(ev) => hideTool(ev)">
        <cube-scroll
          ref="scroll"
          :data="messageList"
          :options="options"
          @pulling-down="onPullingDown"
          :scroll-events="['scroll']"
        >
          <!-- @scroll="onScrollHandle" -->
          <!-- :scroll-events="['scroll']" -->

          <ul class="message-list">
            <li class="list-item" v-for="(item, i) of messageList" :key="i">
              <component :key="i" :is="item.componentName" :chat="item" />
            </li>
          </ul>
        </cube-scroll>
      </div>
      <div class="chat-input-board">
        <chat-board
          @redpacket="onSendRedpacket"
          :shutup="isShutup"
          ref="chatBoard"
          :height="keyboardHeight"
        ></chat-board>
      </div>
    </div>

    <image-preview
      :imageList="imageList"
      :image="previewImage"
      :currentImage="currentImage"
      v-if="showImagePreview"
      @hide="onHideImagePreview"
    />

    <send-redpacket
      @hide="showSendRedpacket = false"
      class="redpacket-comp"
      :class="{'show': showSendRedpacket}"
    />

    <open-redpacket
      :class="{'show': showOpenRedpacket}"
      class="redpacket-comp"
      @hide="showOpenRedpacket = false"
      :packet="packet"
      @open="onOpenRedpacket"
      @detail="onShowRedpacketDetail"
    />

    <!-- <redpacket-detail :class="{'show': showRedpacketDetail}" class="redpacket-comp"  @hide="showRedpacketDetail = false" :packet="packetDetail" :list="detailList" :gotAmount="gotAmount"/> -->
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { forEach } from "lodash";
import { Action, Mutation, Getter, namespace } from "vuex-class";
import {
  Msg,
  Session,
  Webim,
  Text,
  Face,
  Images,
  GroupTip,
  Sound,
  Custom
} from "@/utils/types";
import {
  MsgTypeKV,
  MsgTypeVK
} from "@/api/socket/imClient";
import { Response } from "@/api/bean";
import MessageMixin from "@/mixins";
import { FaceList } from "@/utils/constants";
import { formPost, getTimeString } from '@/utils/common';
declare const $Vue: Vue;
declare const webim: Webim;
declare const wx: any;
const chatModule = namespace("chatModule");
const userModule = namespace("userModule");

@Component<ChatPanel>({
  mixins: [MessageMixin]
})
export default class ChatPanel extends Vue {
  /**
   * 全局变量
   */
  @userModule.State("selToID") selToID: any;
  @userModule.State("selSess") selSess: any;
  @userModule.State("selType") selType: any;
  @userModule.State("loginInfo") loginInfo: any;
  @userModule.State("friendHeadUrl") friendHeadUrl: any;
  @userModule.State("memberInfo") memberInfo: any;
  @userModule.Action("saveMemberInfoFN") saveMemberInfoFN: any;
  @userModule.Action("saveSelSessFN") saveSelSessFN: any;
  @userModule.Action("saveSelToIDFN") saveSelToIDFN: any;

  @chatModule.State("currentGroup") currentGroup: any;
  @chatModule.State("groupSetting") groupSetting: any;
  @chatModule.State("recentSessMap") recentSessMap: any;
  @chatModule.State("wxShareData") wxShareData: any;

  @chatModule.State("getPrePageGroupHistroyMsgInfoMap")
  getPrePageGroupHistroyMsgInfoMap: any;
  @chatModule.Action("saveCurrentGroupFN") saveCurrentGroupFN: any;
  @chatModule.Action("saveGroupSettingFN") saveGroupSettingFN: any;
  @chatModule.Action("saveRecentSessMapFN") saveRecentSessMapFN: any;
  @chatModule.Action("saveGetPrePageGroupHistroyMsgInfoMapFN")
  saveGetPrePageGroupHistroyMsgInfoMapFN: any;
  @chatModule.Action("saveGroupListFN") saveGroupListFN: any;
  @chatModule.State("storeGroupList") storeGroupList: any;

  @userModule.State("groupMembers") groupMembers: any;
  @userModule.Action("saveGroupMembersFN") saveGroupMembersFN: any;

  private title: string = "首页";

  private size: number = 10;
  private offset: number = 10;

  private group: any = {
    groupNick: "",
  };

  private showChatCard: boolean = false;
  //
  private cardType: number = 0;
  // 聊天置顶卡片信息
  private chatCard: any = {};

  // 红包信息
  private packet: any = {
    headUrl: '',
    userNick: '234'
  };
  // 红包详情
  private packetDetail: any = {
    headUrl: '',
    userNick: '234'
  };

  private messageList: Array<any> = [];

  // 红包详情列表
  private detailList: Array<any> = [];

  // 成员id昵称映射
  private membersMap: any = {};

  private options: any = {
    preventDefault: false,
    pullDownRefresh: {
      txt: '...',
      threshold: 60,
      stop: 40,
    },
  };

  private pullDownY: number = 0;
  private pullDownStyle: string = "";
  private opacityStyle: string = "";
  private triggerSurpriseFlag: boolean = false;
  private triggerSurprise: boolean = false;

  // 禁言
  private isShutup: boolean = false;

  private showSendRedpacket: boolean = false;
  private showOpenRedpacket: boolean = false;
  private showRedpacketDetail: boolean = false;

  private listStyle: any = {};
  private scrollStyle: any = {};
  // 聊天面板样式
  private panelStyle: any = {
    bottom: '0px'
  };

  // 预览图片列表
  private imageList: Array<any> = [];
  // 当前预览index
  private currentImage: number = -1;

  private showImagePreview: boolean = false;

  private newMember: boolean = false;
  private initialed: boolean = false;
  private newMemberId: string = '';
  private gotAmount: any = '';
  private previewImage: any = '';

  private showTool: boolean = false;

  private eventList: Array<string> = [
    "onMsgNotify",
    "onKickedEventCall", // 被其他登录实例踢下线
    // "onApplyJoinGroupRequestNotify", //申请加群请求（只有管理员会收到）
    // "onApplyJoinGroupAcceptNotify", // 申请加群被同意（只有申请人能够收到）
    // "onKickedGroupNotify", // 被管理员踢出群（只有被踢者接收到）
    // "onDestoryGroupNotify", // 群被解散（全员接收）
    // "onCreateGroupNotify", // 创建群（创建者接收）
    // "onInvitedJoinGroupNotify", // 邀请加群（被邀请者接收）
    // "onQuitGroupNotify", // 主动退群（主动退出者接收）
    // "onSetedGroupAdminNotify", // 设置管理员（被设置者接收）
    // "onCanceledGroupAdminNotify", // 取消管理员（被取消者接收）
    // "onRevokeGroupNotify", // 群已被回收（全员接收）
    "onCustomGroupNotify", // 用户自定义通知（默认全员接收）
    "onImagePreview", // 图片预览消息
    "onHeadClicked", // 点击头像
    // "onHeadPressed", // 长按头像
    "onWindowSizeChange", // 点击头像
    "setShowTool", // 点击头像
    "onOpenRedpacket", // 点击头像
    "onShowRedpacketDetail", // 点击头像
    "$enterGroupChat",
    "$quitGroupChat",
    "$getTopFixedCard",
    "$clickTopFixedCard",
    "$getGroupInfoByGroupId",
    // "$getWxShare",
    "$getMemberList",
    "$shutUpOff",
    "$shutUpOn",
    "$getBattleImage",
    "$getShareCard",
    "$getUserQrcode",
  ];

  private get pullDownTip() {
    if (this.pullDownY <= 60) {
      return "下拉刷新...";
    } else if (this.pullDownY <= 90) {
      return "继续下拉有惊喜...";
    } else {
      return "松手得惊喜！";
    }
  }

  private get headerStyle() {
    return Math.min(1, Math.max(0, 1 - this.pullDownY / 40));
  }

  private fullHeight: any = 0;
  private keyboardHeight: any = 0;

  protected mounted() {

    this.fullHeight = window.innerHeight;

    // this.wxShare(this.wxShareData)

    // 初始化全局事件
    this.initEvents(this.eventList);

    this.calcPanelStyle();

    window.onresize = (ev: any) => {
      setTimeout(() => {
        this.keyboardHeight = Number(this.fullHeight - window.innerHeight);
      }, 600);
    };

    this.initChat();

    // window.onresize = (ev: any) => {
    //   this.$nextTick(() => {
    //     let wrapper: any = document.querySelector('.chatpanel-container');

    //     let height = 500;
    //     if (wrapper) {
    //       height = wrapper.scrollHeight;
    //     } else {
    //       return;
    //     }

    //     let paddingHeight = 44 + 50;

    //     // 修改消息列表样式
    //     this.listStyle = {
    //       height: (height - paddingHeight) + 'px',
    //       top: '44px',
    //       bottom: '50px',
    //     };

    //     this.scrollStyle = {
    //       'min-height': (height - paddingHeight) + 'px',
    //     };

    //     let scrollList: any = document.querySelector('.cube-scroll-list-wrapper');
    //     scrollList.style = {
    //       'min-height': (height - paddingHeight) + 'px',
    //     };

    //     this.$forceUpdate();
    //     this.scrollToEnd();
    //   })
    // }

    // 进入群聊
    // let params: any = this.$route.params;
    this.group = this.currentGroup;

    this.sendMessage(MsgTypeKV.enterGroupChat, {
      groupId: this.group.groupId,
      signUrl: window.location.href
    });


    if (this.group.groupNick) {
      let groupNick = this.group.groupNick.length > 10 ? this.group.groupNick.substring(0, 10) : this.group.groupNick;
      document.title = `${groupNick} (群号: ${this.group.groupId})`;
    }

    if (!this.group.imGroupId) {
      return this.$router.push({
        name: "Chat",
      });
    }

  }

  private addToMsgList(msg: any, history: boolean) {
    if (history) {
      this.messageList.splice(0, 0, msg);
    } else {
      this.messageList.push(msg);
      this.$nextTick(()=>{
        this.scrollToEnd();
      });
    }

  }

  private calcPanelStyle() {
    let bodyHeight: any = document.body.scrollHeight;
    let barHeight = 36;
    let listHeight = bodyHeight - barHeight;
    this.panelStyle = {
      height: listHeight + 'px',
      bottom: '0px',
    };

  }

  /**
   * 获取完群成员列表之后启动
   */
  private initChat() {
    sessionStorage.setItem("groupId", this.group.groupId);
    sessionStorage.setItem("selToID", this.group.imGroupId);
    this.saveSelToIDFN(this.group.imGroupId);
    // 切换群聊对象

    let skey = "GROUP" + this.group.imGroupId;
    let sessMap = webim.MsgStore.sessMap(); // 获取 sessMap
    let selSess = sessMap[skey]; // 获取 Session 的实例
    if (selSess) {
      this.getLastGroupHistoryMsgs((msgList) => {
        msgList.forEach((item) => {
          this.addMsg(item, false);
        });
      });
      // let msgList = selSess.msgs();
      // if (msgList.length < 1) {
      // this.getGroupMessages();
      // } else {
      // this.showMsgList();
      // }
      webim.setAutoRead(selSess, true, true);
    }
    this.setMessageRead();
  }

  /**
   * 设置本地的未读显示
   */
  private setLocalAutoRead() {
    let skey = "GROUP" + this.group.imGroupId;
    let localUnreadMap: any = localStorage.getItem('readMap');
    if (localUnreadMap) {
      localUnreadMap = JSON.parse(localUnreadMap);
    } else {
      localUnreadMap = {};
    }

  }

  /**
   * 开关工具箱 调整列表大小
   */
  private onWindowSizeChange(show: boolean) {

    let bottomHeight = 54;
    if (show) {
      bottomHeight = 188;
    }
    // this.$nextTick(() => {
    //   let wrapper: any = document.querySelector('.chatpanel-container');

    //   let height = 500;
    //   if (wrapper) {
    //     height = wrapper.scrollHeight;
    //   } else {
    //     return;
    //   }

    //   let paddingHeight = 44 + bottomHeight;

    //   // 修改消息列表样式
    //   this.listStyle = {
    //     height: (height - paddingHeight) + 'px',
    //     top: '44px',
    //     bottom: `${bottomHeight}px`,
    //   };

    //   this.scrollStyle = {
    //     'min-height': (height - paddingHeight) + 'px',
    //   };

    //   let scrollList: any = document.querySelector('.cube-scroll-list-wrapper');
    //   scrollList.style = {
    //     'min-height': (height - paddingHeight) + 'px',
    //   };

    //   this.$forceUpdate();
    //   this.scrollToEnd();
    // })
  }

  private setShowTool(val) {
    this.showTool = val;
    let bottom = 200;
    if (this.keyboardHeight) {
      bottom = this.keyboardHeight;
    }
    if (!this.showTool) {
      bottom = 0;
    }
    // this.panelStyle.bottom = bottom;
    this.$set(this.panelStyle, 'bottom', bottom + 'px');
  }

  private scrollToEnd() {
    let scroll: any = this.$refs.scroll;
    if (scroll) {
      this.$nextTick(() => {
        let list: any = document.querySelector(".message-list");
        let height;
        if (list) {
          height = list.scrollHeight;
          scroll.refresh();
          if (height > 550) {
            scroll.scrollTo(0, - height, 1, true);
          }
        }
      });
    }
  }

  private addMsgList(msgList: Array<any>, history: boolean) {
    // msgList.sort((a, b) => {
    //   return a.time - b.time;
    // })
    //   .forEach((item, i) => {
    //     this.addMsg(item, history);
    //     if (i === msgList.length - 1) {
    //       this.scrollToEnd();
    //     }
    //   })
  }


  private showMsgList() {
    // let skey = "GROUP" + this.group.imGroupId;

    // let sessMap = webim.MsgStore.sessMap(); // 获取 sessMap
    // let selSess = sessMap[skey]; // 获取 Session 的实例
    // if (selSess) {
    //   let msgList: Array<any> = selSess.msgs();
    //   this.addMsgList(msgList)
    // }
  }

  private deleteSessions() {
    let sessMap = webim.MsgStore.sessMap();
    for (let key in sessMap) {
      webim.MsgStore.delSessByTypeId(this.selType, key.replace(this.selType, ''));
    }
  }


  private getGroupMessages() {
    this.deleteSessions();
    this.getGroupInfo(
      this.group.imGroupId,
      resp => {
        // console.error("getGroupInfo", resp);
        let options = {
          GroupId: this.group.imGroupId,
          ReqMsgSeq: resp.GroupInfo[0].NextMsgSeq - 1,
          ReqMsgNumber: 50,
        };
        if (
          options.ReqMsgSeq == null ||
          options.ReqMsgSeq == undefined ||
          options.ReqMsgSeq <= 0
        ) {
          webim.Log.warn(
            "该群还没有历史消息:options=" + JSON.stringify(options)
          );
          return;
        }
        webim.syncGroupMsgs(
          options,
          msgList => {
            // this.addMsgList(msgList);
          },
          err => {
            // this.$createToast({
            //   txt: err.ErrorInfo,
            //   type: "warn",
            //   time: 3000
            // }).show();
          }
        );
      },
      () => { }
    );
  }

  /**
   * 获取群历史消息
   */
  private getLastGroupHistoryMsgs(cbOK?: Function) {
    // selToID 为全局变量，表示当前正在进行的聊天 ID，当聊天类型为私聊时，该值为好友帐号，否则为群号。
    this.deleteSessions();
    this.getGroupInfo(
      this.group.imGroupId,
      (resp: any) => {
        let options = {
          GroupId: this.group.imGroupId,
          ReqMsgSeq: resp.GroupInfo[0].NextMsgSeq - 1,
          ReqMsgNumber: 10,
        };
        if (
          options.ReqMsgSeq == null ||
          options.ReqMsgSeq == undefined ||
          options.ReqMsgSeq <= 0
        ) {
          webim.Log.warn(
            "该群还没有历史消息:options=" + JSON.stringify(options)
          );
          this.$createToast({
              txt: "该群还没有历史消息",
              type: "warn",
              time: 3000
            }).show();
          return;
        }
        this.saveSelSessFN(null);
        webim.MsgStore.delSessByTypeId(this.selType, this.selToID);
        let map = {};
        let skey = webim.SESSION_TYPE.GROUP + '_' + this.selToID
        map[skey] = {
          MsgGroupReadedSeq: resp.GroupInfo && resp.GroupInfo[0] && resp.GroupInfo[0].MsgSeq,
        };
        this.saveRecentSessMapFN(map);
        webim.syncGroupMsgs(
          options,
          (msgList: Array<any>) => {
            if (msgList.length == 0) {
              webim.Log.warn("该群没有历史消息了:options=" + JSON.stringify(options));
            this.$createToast({
              txt: "该群没有历史消息了",
              type: "warn",
              time: 3000
            }).show();
              return;
            }
            var msgSeq = msgList[0].seq - 1;
            let map = {};
            map[this.selToID] = {
              "ReqMsgSeq": msgSeq
            };
            this.saveGetPrePageGroupHistroyMsgInfoMapFN(map);
            //清空聊天界面
            if (cbOK) {
              cbOK(msgList);
            } else {
              this.getHistoryMsgCallback(msgList, false);
            }
          },
          (err: any) => {
            this.$createToast({
              txt: err.ErrorInfo,
              type: "warn",
              time: 3000
            }).show();
          }
        );

      },
      () => { }
    );
  }

  /**
   * 向上翻页时获取更早的群历史消息
   */
  private getPrePageGroupHistoryMsgs(cbOK?: Function) {
    // 获取下一次拉取的群消息seq
    this.deleteSessions();
    let tempInfo = this.getPrePageGroupHistroyMsgInfoMap[this.group.imGroupId];
    let reqMsgSeq;
    if (tempInfo) {
      reqMsgSeq = tempInfo.ReqMsgSeq;
      if (reqMsgSeq <= 0) {
          this.$createToast({
              txt: "该群没有历史消息了",
              type: "warn",
              time: 3000
            }).show();
        return;
      }
    } else {
      webim.Log.error("获取下一次拉取的群消息seq为空");
      return;
    }
    let options = {
      GroupId: this.group.imGroupId,
      ReqMsgSeq: reqMsgSeq,
      ReqMsgNumber: 10
    };
    webim.syncGroupMsgs(
      options,
      (msgList: Array<any>) => {
        if (msgList.length == 0) {
          webim.Log.warn("该群没有历史消息了:options=" + JSON.stringify(options));
           this.$createToast({
              txt: "该群没有历史消息了",
              type: "warn",
              time: 3000
            }).show();
          return;
        }
        let msgSeq = msgList[0].seq - 1;
        let map = {};
        map[this.selToID] = {
          "ReqMsgSeq": msgSeq,
        };
        this.saveGetPrePageGroupHistroyMsgInfoMapFN(map)
        if (cbOK) {
          cbOK(msgList);
        } else {
          this.getHistoryMsgCallback(msgList, true);
        }
      },
      err => { }
    );
  }

  /**
   * 获取的历史消息回调
   */
  private getHistoryMsgCallback(msgList: Array<any>, history: boolean) {
    let msg;
    history = history || false;
    // 如果是加载前几页的消息，消息体需要prepend，所以先倒排一下
    if (history) {
      msgList.reverse();
    }
    for (let j in msgList) { //遍历新消息
      msg = msgList[j];
      if (msg.getSession().id() == this.selToID) { //为当前聊天对象的消息
        let selSess = msg.getSession();
        //在聊天窗体中新增一条消息
        this.addMsg(msg, history);
        this.saveSelSessFN(selSess);
      }
    }
    //消息已读上报，并将当前会话的消息设置成自动已读
    webim.setAutoRead(this.selSess, true, true);

  }

  /**
   * 获取群资料
   */
  private getGroupInfo(group_id, cbOK, cbErr) {
    let options = {
      GroupIdList: [group_id],
      GroupBaseInfoFilter: [
        "Type",
        "Name",
        "Introduction",
        "Notification",
        "FaceUrl",
        "CreateTime",
        "Owner_Account",
        "LastInfoTime",
        "LastMsgTime",
        "NextMsgSeq",
        "MemberNum",
        "MaxMemberNum",
        "ApplyJoinOption",
        "ShutUpAllMember",
      ],
      MemberInfoFilter: [
        "Account",
        "Role",
        "JoinTime",
        "LastSendMsgTime",
        "ShutUpUntil"
      ]
    };
    webim.getGroupInfo(
      options,
      (resp) => {
        console.error("getGroupInfo", resp);
        if (resp.GroupInfo[0].ShutUpAllMember == "On") {
          console.error("该群组已开启全局禁言");
        }
        if (cbOK) {
          cbOK(resp);
        }
      },
      (err) => {
        // this.$createToast({
        //   txt: err.ErrorInfo,
        //   type: "warn",
        //   time: 3000
        // }).show();
      }
    );
  }

  /**
   * 设置消息已读
   */
  private setMessageRead() {
    let skey = "GROUP" + this.group.imGroupId;
    let sessMap = webim.MsgStore.sessMap(); // 获取 sessMap
    let selSess = sessMap[skey]; // 获取 Session 的实例
    if (selSess) {
      console.warn("setMessageRead", selSess);
      webim.setAutoRead(selSess, true, true);
    }
  }

  private onFetch() {
    let items: any = [];
    return new Promise(resolve => {
      // 模拟请求 50 条数据，因为 size 设置为 50
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          items.push();
        }
        resolve(items);
      }, 1000);
    });
  }

  /**
   * 打开图片预览
   */
  private onImagePreview(image: any) {
    // let image = data.data;
    // let list: Array<any> = [];
    // this.messageList.forEach((item: any) => {
    //   if (item.componentName === "message-photo") {
    //     list.push({
    //       image: item.content
    //     });
    //   }
    // });
    // this.imageList = list;
    // this.showImagePreview = true;

    // this.previewImage = data;
    this.previewImage = image;
    this.showImagePreview = true;
  }

  /**
   * 点击头像获取二维码
   */
  private onHeadClicked(chat: any) {

    this.saveMemberInfoFN(chat.data);
    this.$router.push({
      name: 'MemberInfo',
    });

    // this.sendMessage(MsgTypeKV.getUserQrcode, {
    //   imAccount: chat.data.fromAccount
    // });
    // this.previewImage = image;
    // this.showImagePreview = true;

  }




  /**
   * 发红包
   */
  private onSendRedpacket() {
    this.showSendRedpacket = true;
  }

  /**
   * 抢红包
   */
  private onOpenRedpacket(data) {
    this.showOpenRedpacket = true;
    this.showSendRedpacket = false;
    this.packet = data.data;
  }

  /**
   * 抢到的红包详情
   */
  private onShowRedpacketDetail(data) {
    // this.showRedpacketDetail = true;
    this.showOpenRedpacket = false;
    this.$router.push({
      name: 'RedpacketDetail',
      params: data.data,
    });
    // this.$set(this,'packetDetail', data.data )

  }

  private onHideImagePreview() {
    this.showImagePreview = false;
  }

  private onPullingDown() {
    let scroll: any = this.$refs.scroll;
    this.getPrePageGroupHistoryMsgs();
    if (this.triggerSurpriseFlag) {
      this.triggerSurprise = true;
      scroll.forceUpdate();
      return;
    }
    setTimeout(() => {
      scroll.forceUpdate();
    }, 1000);
  }

  /**
   * 列表滚动 关闭Toolbox
   */
  private onScrollHandle(pos) {
    this.pullDownY = pos.y;
    if (pos.y > 0) {
      this.pullDownStyle = `top:${pos.y}px`;
      this.triggerSurpriseFlag = false;
      if (this.pullDownY > 90) {
        this.triggerSurpriseFlag = true;
      }
    }
    $Vue.$emit('hideToolBox');

    // this.$refs.topHeader.style.opacity = this.headerStyle
  }

  private hideTool() {
    $Vue.$emit('hideToolBox');
  }

  private onPullingUp() { }

  /**
   * 接收消息
   */
  private onMsgNotify(newMsgList: Array<Msg>) {
    console.warn("onMsgNotify 收到新消息", newMsgList);

    newMsgList.forEach((msg: any, index: number) => {
      let groupList = this.storeGroupList.slice();

      groupList.forEach((item: any, i: any) => {
        if (msg.sess._impl.id === item.imGroupId) {
          let msgList = msg.sess.msgs();

          let list: Array<any> = [];
          msgList.forEach((item: any) => {
            list.push({
              elems: item.elems,
              extraInfo: item.extraInfo,
              fromAccount: item.fromAccount,
              fromAccountHeadurl: item.fromAccountHeadurl,
              fromAccountNick: item.fromAccountNick,
              isSend: item.isSend,
              seq: item.seq,
              subType: item.subType,
              time: item.time,
              uniqueId: item.uniqueId,
              LastMsg: {},
            });
          });
          // 最后一条消息不取系统消息
          let last = list.length - 1;
          if (last <= 0) {
            last = 0;
          } else {
            let msgType = list[last].elems[0].type;
            let contentType = ''
            if (msgType == "TIMCustomElem") {
              contentType = list[last].elems[0].content.desc;
            }
            while (list[last].subType === webim.GROUP_MSG_SUB_TYPE.TIP && contentType == 'message-tip') {
              last--;
            }
          }

          groupList[i].msgList = list;
          let time = list[last].time;
          if (!time) {
            time = 0;
          }
          if (groupList[i].isTop) {
            time = (new Date().getTime()) + 10000 * i;
          }
          if (time.toString().length <= 10) {
            time = time * 1000;
          }
          groupList[i].lastTime = time
          groupList[i].LastMsgTime = getTimeString(list[last].time, false)
          groupList[i].LastMsg = list[last];
        }
      });

      // if (index === (newMsgList.length - 1)) {
      this.saveGroupListFN(groupList);
      // }
    });

    let sess: Session;
    let sessMap: any = webim.MsgStore.sessMap();
    forEach(newMsgList, newMsg => {
      if (newMsg.getSession().id() === this.selToID) {
        let selSess = newMsg.getSession();
        this.saveSelSessFN(selSess);
        webim.setAutoRead(selSess, true, true);
        this.addMsg(newMsg, false);
        this.scrollToEnd()
      }
    });
    // 消息已读上报
    // forEach(sessMap, sess => {
    //   if (this.selToID !== sess.id()) {
    //     // 更新其他聊天对象的未读消息数
    //     // this.updateSessDiv(sess.type(), sess.id(), sess.unread());
    //   }
    // });
  }

  private onSetting() {
    this.$router.push({
      name: "GroupSetting",
    });
  }

  /**
   * 点击置顶卡片type = 1为将param以json格式post方式提交到targetUrl
   * type=2，当用户点击的时候就要请求1016这个接口）
   */
  private onChatCardClicked() {
    if (this.chatCard.type == 1) {
      formPost(this.chatCard.targetUrl, this.chatCard.param);
      // console.error(this.chatCard);
    } else if (this.chatCard.type == 2) {
      this.sendMessage(MsgTypeKV.clickTopFixedCard);
    }
  }

  /**
   * 退出群聊返回上一级
   */
  private onQuitGroupChat() {
    this.sendMessage(MsgTypeKV.quitGroupChat);
    this.$router.push({
      name: 'Chat'
    });
  }

  /**
   * 转换分享卡片
   */
  private convertShareCard(content: Custom, history: boolean) {
    let card: any;
    try {
      let data = JSON.parse(content.getData())
      if (data.UserDefinedField) {
        // card = JSON.parse(data.UserDefinedField)
        return;
      } else {
        card = data;
      }
      // card = JSON.parse(JSON.parse(content.getData()).UserDefinedField);

      let msg = {
        ...card,
        componentName: 'message-card'
      };
    this.addToMsgList(msg, history)
      let chatBoard: any = this.$refs.chatBoard
      if (chatBoard) {
        chatBoard.showTool = false;
      }
    } catch (err) {
    }
  }


  /**
   * 转换自定义提示消息
   */
  private convertCustomTip(content: Custom, history: boolean) {

    let card: any;
    try {
      let data = JSON.parse(content.getData())
      // console.warn('-----------tip', data);

      let ext = JSON.parse(content.getExt());
      let operatorName = ext.operatorName;
      let tip = ''
      // 如果是自己发送的
      if (localStorage.getItem('userId') == ext.operatorId) {
        operatorName = '你';
        tip = `你 ${data.content}`;
      } else {
        tip = `<span class="emp-name">${operatorName}</span> ${data.content}`;
      }

      let msg = {
        content: tip,
        componentName: 'message-tip'
      };
    this.addToMsgList(msg, history)
    } catch (err) {
      // this.$createToast({
      //   txt: JSON.stringify(err),
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 转换战绩图消息
   */
  private convertCustomBattle(content: Custom, history: boolean) {

    let card: any;
    try {
      let data = JSON.parse(content.getData())
      // let ext = JSON.parse(content.getExt());
      // console.error('convertCustomBattleconvertCustomBattle', data);

      let msg = {
        content: data,
        componentName: 'message-battle'
      };
          this.addToMsgList(msg, history)
    } catch (err) {
      // this.$createToast({
      //   txt: JSON.stringify(err),
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 转换红包消息
   */
  private convertCustomRedpacket(content: Custom, options: any, history: boolean) {

    let card: any;
    try {
      let data = JSON.parse(content.getData())
      let msg = {
        content: data,
        componentName: 'message-redpacket',
        role: options.role,
        fromAccount: options.fromAccount,
        fromAccountNick: options.fromAccountNick,
        isSelf: options.isSelf,
        fromAccountHeadurl: options.fromAccountHeadurl
      };
          this.addToMsgList(msg, history)
    } catch (err) {
      // this.$createToast({
      //   txt: JSON.stringify(err),
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 微信签名
   */
  private wxShare(data: any) {
    // alert(this.wxShareData.shareLink)
    // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
    wx.updateAppMessageShareData({
      title: `${this.groupSetting.info.groupNick} 群号: (${this.groupSetting.info.groupId})`, // 分享标题
      desc: "", // 分享描述
      link: this.wxShareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: this.groupSetting.managerInfo.headUrl, // 分享图标
      success: () => {
        // 设置成功
      }
    });
    // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
    wx.updateTimelineShareData({
      title: `${this.groupSetting.info.groupNick} 群号: (${this.groupSetting.info.groupId})`, // 分享标题
      link: this.wxShareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: this.groupSetting.managerInfo.headUrl, // 分享图标
      success: () => {
        // 设置成功
      }
    });
  }

  /**
   * 聊天记录新增一条消息
   */
  private addMsg(msg: Msg, history: boolean) {
    // console.warn("聊天记录新增一条消息", msg);

    let isSelf, fromAccount, fromAccountNick, sessType, subType;
    // 其他附加的选项

    fromAccount = msg.fromAccount;
    if (!fromAccount) {
      fromAccount = "???";
    }
    fromAccountNick = msg.fromAccountNick;
    if (!fromAccountNick) {
      fromAccountNick = fromAccount;
    }
    isSelf = msg.isSend; //消息是否为自己发的

    //获取会话类型，目前只支持群聊
    //webim.SESSION_TYPE.GROUP-群聊，
    //webim.SESSION_TYPE.C2C-私聊，
    // sessType = msg.getSession().type();
    //获取消息子类型
    //会话类型为群聊时，子类型为：webim.GROUP_MSG_SUB_TYPE
    //会话类型为私聊时，子类型为：webim.C2C_MSG_SUB_TYPE
    subType = msg.subType;
    let fromAccountHeadurl = msg.fromAccountHeadurl;
    if (fromAccountHeadurl === null) {
      fromAccountHeadurl = "";
    }
    let options = {
      fromAccount,
      fromAccountNick,
      fromAccountHeadurl,
      isSelf,
      role: msg.extraInfo.Role
    };
    switch (subType) {
      case webim.GROUP_MSG_SUB_TYPE.COMMON: //群普通消息
        // 将消息转换成对应的组件显示
        this.convertMsgToComponent(msg, options, history);
        break;
      case webim.GROUP_MSG_SUB_TYPE.REDPACKET: //群红包消息
        break;
      case webim.GROUP_MSG_SUB_TYPE.LOVEMSG: //群点赞消息
        //业务自己可以增加逻辑，例如展示点赞动画效果
        //展示点赞动画
        //showLoveMsgAnimation();
        break;
      case webim.GROUP_MSG_SUB_TYPE.TIP: //群提示消息
        this.convertMsgToComponent(msg, options, history);
        break;
    }

    // TODO 300ms 后,等待图片加载完，滚动条自动滚动到底部
  }

  /**
   * 转换一条消息
   */
  private convertMsgToComponent(msg: Msg, options: any, history: boolean) {
    let html = "",
      elems,
      elem,
      type,
      content;
    elems = msg.elems; // 获取消息包含的元素数组

    // 转换
    let msgType = 0;
    forEach(elems, elem => {
      type = elem.getType(); // 获取元素类型
      content = elem.getContent(); // 获取元素对象
      switch (type) {
        case webim.MSG_ELEMENT_TYPE.TEXT:
          html += this.convertTextMsg(content, options);
          msgType = 1;
          break;
        case webim.MSG_ELEMENT_TYPE.FACE:
          html += this.convertFaceMsg(content, options);
          msgType = 1;
          break;
        case webim.MSG_ELEMENT_TYPE.IMAGE:
          this.convertImageMsg(content, options, history);
          break;
        case webim.MSG_ELEMENT_TYPE.SOUND:
          // this.convertSoundMsg(content, options);
          break;
        case webim.MSG_ELEMENT_TYPE.FILE:
          // this.convertTextMsg(content);
          break;
        case webim.MSG_ELEMENT_TYPE.LOCATION: //暂不支持地理位置
          //html += convertLocationMsgToHtml(content);
          break;
        case webim.MSG_ELEMENT_TYPE.CUSTOM:
          // 作为音频消息解读
          this.convertCustomMsg(content, options, history);
          // this.convertTextMsg(content);
          break;
        case webim.MSG_ELEMENT_TYPE.GROUP_TIP:
          // this.convertTextMsg(content);
          this.convertGroupTipMsg(content, options, history);
          break;
        default:
          webim.Log.error("未知消息元素类型: elemType=" + type);
          break;
      }
    });

    // 文本+表情
    if (msgType === 1) {
      let msg = {
        content: html,
        role: options.role,
        fromAccount: options.fromAccount,
        fromAccountNick: options.fromAccountNick,
        componentName: "message-text",
        isSelf: options.isSelf,
        fromAccountHeadurl: options.fromAccountHeadurl
      };
    this.addToMsgList(msg, history)
    }
  }

  /**
   * 计算日期间隔显示
   */
  private calcTimeTip() { }

  /**
   * 解析文本消息
   */
  private convertTextMsg(text: Text, options: any) {
    let msg = `<span class='msg-text'>${text.getText()}</span>`;
    return msg;
  }

  /**
   * 解析表情消息
   */
  private convertFaceMsg(face: Face, options: any) {
    let index = face.getIndex();
    let data = face.getData();
    let url = null;
    let content;

    if (FaceList[data] === index) {
      let face = require(`@/assets/emoji/${index}.gif`);
      content = `<img src="${face}" class="face-image"/>`;
    } else {
      content = data;
    }
    return content;
  }

  /**
   * 解析图片消息
   */
  private convertImageMsg(image: Images, options: any, history: boolean) {
    let smallImage = image.getImage(webim.IMAGE_TYPE.SMALL); //小图
    let bigImage = image.getImage(webim.IMAGE_TYPE.LARGE); //大图
    let oriImage = image.getImage(webim.IMAGE_TYPE.ORIGIN); //原图
    if (!bigImage) {
      bigImage = smallImage;
    }
    if (!oriImage) {
      oriImage = smallImage;
    }

    let msg = {
      smallImage: smallImage.getUrl(),
      bigImage: bigImage.getUrl(),
      oriImage: oriImage.getUrl(),
      id: image.getImageId(),
      role: options.role,
      fromAccount: options.fromAccount,
      fromAccountNick: options.fromAccountNick,
      componentName: "message-photo",
      isSelf: options.isSelf,
      fromAccountHeadurl: options.fromAccountHeadurl
    };
    this.addToMsgList(msg, history);
  }

  /**
   * 转换自定义消息
   */
  private convertCustomMsg(msg: Custom, options: any, history: boolean) {
    let desc = msg.getDesc();
    switch (desc) {
      case "message-sound": {
        // 转为语音播放
        this.convertSoundMsg(msg, options, history);
        break;
      }
      case "message-card": {
        // 转为分享卡片
        this.convertShareCard(msg, history);
        break;
      }
      case "message-tip": {
        // 转为分享卡片
        this.convertCustomTip(msg, history);
        break;
      }
      case "message-battle": {
        // 转为战绩图片
        this.convertCustomBattle(msg, history);
        break;
      }
      case "message-redpacket": {
        // 转为红包消息
        this.convertCustomRedpacket(msg, options, history);
        break;
      }
    }
  }

  /**
   * @description 解析语音消息
   * @uses amr音频信息转使用amr.js播放
   * @param {Object.<{uuid:string,downUrl:string}>} content - 消息内容对象
   * @property {string} uuid - 文件的 UUID
   * @property {string} downUrl - 文件的下载地址
   * @returns {string||null} aElmentString - AMR播放控件的 HTML 代码
   */
  private convertSoundMsg(sound: Custom, options: any, history: boolean) {
    // 解析自定义消息中的声音信息
    let data: any = sound.getData();
    let desc = sound.getDesc();
    let ext = sound.getExt();

    try {
      data = JSON.parse(data);
    } catch (err) {
      console.error(err);
    }

    let msg = {
      data,
      role: options.role,
      fromAccount: options.fromAccount,
      fromAccountNick: options.fromAccountNick,
      componentName: "message-sound",
      isSelf: options.isSelf,
      fromAccountHeadurl: options.fromAccountHeadurl
    };

    this.addToMsgList(msg, history);

  }

  /**
   * 解析位置消息
   */
  private convertLocationMsg() { }

  /**
   * 解析群提示消息
   */
  private convertGroupTipMsg(tip: GroupTip, options: any, history: boolean) {
    let WEB_IM_GROUP_TIP_MAX_USER_COUNT = 6;
    let text = "";
    let maxIndex: any = WEB_IM_GROUP_TIP_MAX_USER_COUNT - 1;
    let opType, opUserId, userInfoList;
    opType = tip.getOpType(); //群提示消息类型（操作类型）
    opUserId = tip.getOpUserId(); //操作人 ID
    let userNameList;
    // 设置管理员
    // if (opType === webim.GROUP_TIP_TYPE.SET_ADMIN) {
    //   let opUserName = '';
    //   if (this.loginInfo.identifier === opUserId) {
    //     opUserName = '你';
    //   } else {
    //     opUserName = `<span>${this.loginInfo.identifierNick}</span>`
    //   }
    //   text += opUserName + "将";
    //     userInfoList = tip.getUserIdList();
    //     for (let i = 0; i < userInfoList.length; i++) {
    //       text += this.membersMap[userInfoList[i]] + ",";
    //       if (
    //         userInfoList.length > WEB_IM_GROUP_TIP_MAX_USER_COUNT &&
    //         i == maxIndex
    //       ) {
    //         text += "等" + userInfoList.length + "人";
    //         break;
    //       }
    //     }
    //     text += "设置为管理员";
    // } else if(opType ===              webim.GROUP_TIP_TYPE.CANCEL_ADMIN) {
    //   let opUserName = '';
    //   if (this.loginInfo.identifier === opUserId) {
    //     opUserName = '你';
    //   } else {
    //     opUserName = `<span>${this.loginInfo.identifierNick}</span>`
    //   }
    //   text += opUserName + "将";
    //     userInfoList = tip.getUserIdList();
    //     for (let i = 0; i < userInfoList.length; i++) {
    //       text += this.membersMap[userInfoList[i]] + ",";
    //       if (
    //         userInfoList.length > WEB_IM_GROUP_TIP_MAX_USER_COUNT &&
    //         i == maxIndex
    //       ) {
    //         text += "等" + userInfoList.length + "人";
    //         break;
    //       }
    //     }
    //     text += "取消了管理员";
    // } else 
    if (opType === webim.GROUP_TIP_TYPE.MODIFY_GROUP_INFO) {
      // text += opUserId + "修改了群资料：";
      let groupInfoList = tip.getGroupInfoList();
      let type, value;
      for (let m in groupInfoList) {
        type = groupInfoList[m].getType();
        value = groupInfoList[m].getValue();
        switch (type) {
          case webim.GROUP_TIP_MODIFY_GROUP_INFO_TYPE.OWNER: {
            if (value === this.loginInfo.identifier) {
              text += '你已成为新群主';
            } else {
              text += `<span class='emp-name'>"${this.membersMap[value]}"</span>已成为新群主`
            }
          }
            break;
          default:
            return;
        }
      }
    } else {
      return;
    }

    let msg = {
      content: text,
      componentName: "message-tip"
    };

    this.addToMsgList(msg, history);

  }

  private newGroupMember(userInfoList, maxIndex, text, WEB_IM_GROUP_TIP_MAX_USER_COUNT) {
    let userId;
    if (userInfoList.length > 0) {
      userId = userInfoList[0];
    }
    this.newMemberId = userId;
    this.newMember = true;

    this.sendMessage(MsgTypeKV.getMemberList, {
      groupId: this.group.groupId,
    });
  }

  /**
   * 使用自定义消息发送战绩图片信息
   */
  private sendBattleImage(card: any) {
    if (!this.selToID) {
      // selToID 为全局变量，表示当前正在进行的聊天 ID，当聊天类型为私聊时，该值为好友帐号，否则为群号。
      this.$createToast({
        txt: "您还没有选择群，暂不能聊天",
        type: "warn",
        time: 3000
      }).show();
      return;
    }
    let data = JSON.stringify(card);
    let desc = "message-battle";
    let ext = "";
    let msgLen = webim.Tool.getStrBytes(data);
    if (data.length < 1) {
      return;
    }
    let maxLen, errInfo;
    if (this.selType == webim.SESSION_TYPE.C2C) {
      maxLen = webim.MSG_MAX_LENGTH.C2C;
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    } else {
      maxLen = webim.MSG_MAX_LENGTH.GROUP; // 八千字节
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    }
    if (msgLen > maxLen) {
      this.$createToast({
        txt: errInfo,
        type: "warn",
        time: 3000
      }).show();
      return;
    }
    let selSess = webim.MsgStore.sessByTypeId(
      webim.SESSION_TYPE.GROUP,
      this.selToID,
    );
    if (!selSess) {
      selSess = new webim.Session(
        this.selType,
        this.selToID,
        this.selToID,
        this.friendHeadUrl,
        Math.round(new Date().getTime())
      );
      this.saveSelSessFN(selSess);
    }

    let msg = new webim.Msg(
      selSess,
      true,
      -1,
      -1,
      -1,
      this.loginInfo.identifier,
      0,
      this.loginInfo.identifierNick
    );
    let customObj = new webim.Msg.Elem.Custom(data, desc, ext);
    msg.addCustom(customObj);
    //调用发送消息接口
    webim.sendMsg(
      msg,
      (resp) => { },
      (err) => {
        // this.$createToast({
        //   txt: err.ErrorInfo,
        //   type: "warn",
        //   time: 3000
        // }).show();
      }
    );

  }
  /**
   * 使用自定义消息发送卡片信息
   */
  private sendShareCard(card: any) {
    if (!this.selToID) {
      // selToID 为全局变量，表示当前正在进行的聊天 ID，当聊天类型为私聊时，该值为好友帐号，否则为群号。
      this.$createToast({
        txt: "您还没有选择群，暂不能聊天",
        type: "warn",
        time: 3000
      }).show();
      return;
    }
    let data = JSON.stringify(card);
    let desc = "message-card";
    let ext = "share";
    let msgLen = webim.Tool.getStrBytes(data);
    if (data.length < 1) {
      return;
    }
    let maxLen, errInfo;
    if (this.selType == webim.SESSION_TYPE.C2C) {
      maxLen = webim.MSG_MAX_LENGTH.C2C;
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    } else {
      maxLen = webim.MSG_MAX_LENGTH.GROUP; // 八千字节
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    }
    if (msgLen > maxLen) {
      this.$createToast({
        txt: errInfo,
        type: "warn",
        time: 3000
      }).show();
      return;
    }
    let selSess = webim.MsgStore.sessByTypeId(
      webim.SESSION_TYPE.GROUP,
      this.selToID,
    );
    if (!selSess) {
      selSess = new webim.Session(
        this.selType,
        this.selToID,
        this.selToID,
        this.friendHeadUrl,
        Math.round(new Date().getTime())
      );
      this.saveSelSessFN(selSess);
    }

    let msg = new webim.Msg(
      selSess,
      true,
      -1,
      -1,
      -1,
      this.loginInfo.identifier,
      0,
      this.loginInfo.identifierNick
    );
    let customObj = new webim.Msg.Elem.Custom(data, desc, ext);
    msg.addCustom(customObj);
    //调用发送消息接口
    webim.sendMsg(
      msg,
      (resp) => { },
      (err) => {
        // this.$createToast({
        //   txt: err.ErrorInfo,
        //   type: "warn",
        //   time: 3000
        // }).show();
      }
    );

  }

  /**
   * 发送自定义的tip消息
   */
  private sendCustomTip(tip: any) {
    if (!this.selToID) {
      // selToID 为全局变量，表示当前正在进行的聊天 ID，当聊天类型为私聊时，该值为好友帐号，否则为群号。
      this.$createToast({
        txt: "您还没有选择群，暂不能聊天",
        type: "warn",
        time: 3000
      }).show();
      return;
    }

    let data = JSON.stringify(tip.content);
    let desc = "message-tip";
    let ext = tip.ext;
    let msgLen = webim.Tool.getStrBytes(data);
    if (data.length < 1) {
      return;
    }
    let maxLen, errInfo;
    if (this.selType == webim.SESSION_TYPE.C2C) {
      maxLen = webim.MSG_MAX_LENGTH.C2C;
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    } else {
      maxLen = webim.MSG_MAX_LENGTH.GROUP; // 八千字节
      errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    }
    if (msgLen > maxLen) {
      this.$createToast({
        txt: errInfo,
        type: "warn",
        time: 3000
      }).show();
      return;
    }
    let selSess = webim.MsgStore.sessByTypeId(
      webim.SESSION_TYPE.GROUP,
      this.selToID,
    );
    if (!selSess) {
      selSess = new webim.Session(
        this.selType,
        this.selToID,
        this.selToID,
        this.friendHeadUrl,
        Math.round(new Date().getTime())
      );
      this.saveSelSessFN(selSess);
    }

    let msg = new webim.Msg(
      selSess,
      true,
      -1,
      -1,
      -1,
      this.loginInfo.identifier,
      0,
      this.loginInfo.identifierNick
    );
    let customObj = new webim.Msg.Elem.Custom(data, desc, ext);
    msg.addCustom(customObj);
    //调用发送消息接口
    webim.sendMsg(
      msg,
      (resp) => { },
      (err) => {
        // this.$createToast({
        //   txt: err.ErrorInfo,
        //   type: "warn",
        //   time: 3000
        // }).show();
      }
    );

  }

  /**
   * ws 请求
   */

  /**
   * 进入群聊 然后才能发送获取指定卡片消息
   */
  private $enterGroupChat(data: Response<any>) {
    if (data.result === 0) {
      // 获取成员信息
      this.sendMessage(MsgTypeKV.getMemberList, {
        groupId: this.group.groupId,
      });
      // 获取置顶卡片
      this.sendMessage(MsgTypeKV.getTopFixedCard);
      // 获取群聊设置
      this.sendMessage(MsgTypeKV.getGroupInfoByGroupId, {
        groupId: this.group.groupId,
      });

    } else {
      this.$router.go(-1);
      // this.$createToast({
      //   txt: data.message,
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 根据群号搜索群设置信息 用于设置禁言等
   */
  private $getGroupInfoByGroupId(data: any) {
    // console.error( this.$refs.scroll)
    if (data.result === 0) {
      // 是否置顶
      // this.setting.isTop = data.isTop;
      this.isShutup = data.info.isShutup;
      if (this.isShutup) {
        // this.$createToast({
        //   txt: "当前群聊已禁言",
        //   type: "warn",
        //   time: 5000
        // }).show();
        let scroll: any = this.$refs.scroll
        if (scroll && scroll.$el) {
          scroll.$el.focus();
        }
      }
      if (data.status === 1 || data.status === 2) {
        this.isShutup = false;
      }
      // 保存群聊设置
      this.saveGroupSettingFN(data);
      // 配置微信分享
      this.wxShare(data);

    } else {
      this.$createToast({
        txt: '获取群信息失败',
        type: "warn",
        time: 5000
      }).show();
    }
  }
  /**
   * 退出群聊
   */
  private $quitGroupChat(data: Response<any>) {
    if (data.result === 0) {
      // 返回上级页面

    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }

  /**
   * 进入群聊 然后才能发送获取指定卡片消息
   */
  private $getTopFixedCard(data: any) {
    if (data.result === 0) {
      let { info, targetUrl, param } = data;
      if (info.topModel) {
        let topModel: any;
        try {
          topModel = JSON.parse(info.topModel);
        } catch (err) {
          topModel = {};
        }
        this.cardType = topModel.type;
        this.chatCard = {
          ...topModel,
          param,
          targetUrl
        };
        this.showChatCard = true;
        if (!param) {
          this.showChatCard = false;
        }
        // let wrapper: any = document.querySelector('.chatpanel-container');

        // let height = 500;
        // if (wrapper) {
        //   height = wrapper.scrollHeight;
        // } else {
        //   return
        // }

        // let paddingHeight = 44 + 50;

        // // 修改消息列表样式
        // this.listStyle = {
        //   height: (height - paddingHeight) + 'px',
        //   top: '44px',
        //   bottom: '50px',
        // };

        // this.scrollStyle = {
        //   'min-height': (height - paddingHeight) + 'px',
        // };

        // let scrollList: any = document.querySelector('.cube-scroll-list-wrapper');
        // scrollList.style = {
        //   'min-height': (height - paddingHeight) + 'px',
        // };

        // this.$forceUpdate();
        // this.scrollToEnd();

      }
    } else {
      // this.$createToast({
      //   txt: data.message,
      //   type: "correct",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 获取微信分享
   */
  private $getWxShare(data: any) {
    if (data.result === 0) {
      // this.wxShare(data);
    } else {
      // this.$createToast({
      //   txt: data.message,
      //   type: "warn",
      //   time: 3000
      // }).show();
    }
  }

  /**
   * 获取群成员列表
   */
  private $getMemberList(data: any) {
    if (data.result === 0) {
      // this.membersMap = data.infoList;
      // let map = {};
      data.infoList.forEach((item: any) => {
        this.membersMap[item.imAccount] = item.nickname;
      });
      // this.membersMap = map;
      this.saveGroupMembersFN(data.infoList);
      // if (this.newMember) {
      //   let userId;
      //   console.warn('getMemberList', this.newMemberId);

      //   let text = `${this.membersMap[this.newMemberId]}加入该群`;
      //   let content = {
      //     content: text,
      //     componentName: "message-tip"
      //   };
      //   this.newMember = false;

      //   let oldMap: any = localStorage.getItem('MemberMap');
      //   if (oldMap) {
      //     oldMap = JSON.parse(oldMap);
      //   } else {
      //     oldMap = {};
      //   }

      //   localStorage.setItem('MemberMap', JSON.stringify(Object.assign(oldMap, this.membersMap)));

      //   this.messageList.push(content);
      //   this.scrollToEnd();
      // } else {
      // if (!this.initialed) {
      // this.initialed = true;
      // }
      // }
      // 初始化群老
    } else {
      // this.newMember = false;
      // this.$createToast({
      //   txt: data.message,
      //   type: "warn",
      //   time: 3000
      // }).show();
    }

    if (this.newMember) {
      // this.initChat();
    }
    this.initChat();
  }

  /**
   * 根据id获取用户信息
   */
  // private $getMemberInfo(data: any) {

  // }


  /**
   * 开启群聊禁言
   */
  private $shutUpOn(data: any) {
    let content = {
      content: '开启了全员禁言'
    };
    let ext = {
      operatorId: data.operatorId,
      operatorName: data.operatorName,
    };

    this.sendMessage(MsgTypeKV.getGroupInfoByGroupId, {
      groupId: sessionStorage.getItem("groupId")
    });

    if (localStorage.getItem('userId') == data.operatorId) {
      this.sendCustomTip({
        content,
        ext: JSON.stringify(ext),
      });
    }
    // 如果是自己发送的 则发送消息到群中
  }

  /**
   * 关闭群聊禁言
   */
  private $shutUpOff(data: any) {
    let content = {
      content: '关闭了全员禁言'
    };
    let ext = {
      operatorId: data.operatorId,
      operatorName: data.operatorName,
    };
    this.isShutup = false;
    // 如果是自己发送的 则发送消息到群中
    if (localStorage.getItem('userId') == data.operatorId) {
      this.sendCustomTip({
        content,
        ext: JSON.stringify(ext),
      });
    }
  }

  /**
   * 推送的分享卡片
   */
  private $getShareCard(data: any) {
    this.sendShareCard(data);
    this.sendMessage(MsgTypeKV.notifySended, {
      notifyKey: data.nonce,
    });
  }

  /**
   * 推送的战绩图片
   */
  private $getBattleImage(data: any) {
    this.sendBattleImage(data);
    this.sendMessage(MsgTypeKV.notifySended, {
      notifyKey: data.nonce,
    });
  }

  /**
   * 获取到用户qrcode
   */
  private $getUserQrcode(data: any) {
    let payQr = data.info.payQr;
    if (payQr) {
      this.previewImage = payQr;
      this.showImagePreview = true;
    }
  }

  /**
   * 获取到用户qrcode
   */
  private $getRedpacketDetail(data: any) {
    if (data.result === 0) {
      // this.detailList = data.voList;
      this.$set(this, 'detailList', data.voList);
      // alert(data.voList.length);
      // 自己抢到的数目
      // this.gotAmount = data.amount;
      let userId = localStorage.getItem('userId')
      data.voList.forEach((item) => {
        if (item.userId == userId) {
          this.gotAmount = item.amount;
        }
      })
    }
  }



  /**
   * 获取到发送成功的消息后 作为
   */
  private $sendRedpacket(data: any) {
    let payQr = data.info.payQr;
    if (payQr) {
      this.previewImage = payQr;
      this.showImagePreview = true;
    }
  }


  /**
   * 监听新消息（直播聊天室）事件，直播场景下必填
   */
  private onBigGroupMsgNotify() { }

  /**
   * 监听群资料变化事件，选填
   */
  private onGroupInfoChangeNotify() { }

  /**
   * 监听好友系统通知事件，选填
   */
  private onFriendSystemNotifys() { }

  /**
   * 监听资料系统（自己或好友）通知事件，选填
   */
  private onProfileSystemNotifys() { }

  /**
   * 被其他登录实例踢下线
   */
  private onKickedEventCall() {
    alert("多实例登录, 被下线");
    this.$router.push({
      name: 'Chat',
    });
  }

  /**
   * 监听 C2C 系统消息通道
   */
  private onC2cEventNotifys() { }

  /************* 群事件消息 ************/

  /**
   * 申请加群请求（只有管理员会收到）
   */
  private onApplyJoinGroupRequestNotify(data: any) {
    console.error("onApplyJoinGroupRequestNotify", data);
  }

  /**
   * 申请加群被同意（只有申请人能够收到）
   */
  private onApplyJoinGroupAcceptNotify(data: any) {
    console.error("onApplyJoinGroupAcceptNotify", data);
  }

  /**
   * 申请加群被拒绝（只有申请人能够收到）
   */
  private onApplyJoinGroupRefuseNotify(data: any) {
    console.error("onApplyJoinGroupRefuseNotify", data);
  }

  /**
   * 被管理员踢出群（只有被踢者接收到）
   */
  private onKickedGroupNotify(data: any) {
    console.error("onKickedGroupNotify", data);
  }

  /**
   * 群被解散（全员接收）
   */
  private onDestoryGroupNotify(data: any) {
    console.error("onDestoryGroupNotify", data);
  }

  /**
   * 创建群（创建者接收）
   */
  private onCreateGroupNotify(data: any) {
    console.error("onCreateGroupNotify", data);
  }

  /**
   * 邀请加群（被邀请者接收）
   */
  private onInvitedJoinGroupNotify(data: any) {
    console.error("onInvitedJoinGroupNotify", data);
  }

  /**
   * 主动退群（主动退出者接收）
   */
  private onQuitGroupNotify(data: any) {
    console.error("onQuitGroupNotify", data);
  }

  /**
   * 设置管理员（被设置者接收）
   */
  private onSetedGroupAdminNotify(data: any) {
    console.error("onSetedGroupAdminNotify", data);
  }

  /**
   * 取消管理员（被取消者接收）
   */
  private onCanceledGroupAdminNotify(data: any) {
    console.error("onCanceledGroupAdminNotify", data);
  }

  /**
   * 群已被回收（全员接收）
   */
  private onRevokeGroupNotify(data: any) {
    console.error("onRevokeGroupNotify", data);
  }

  /**
   * 用户自定义通知（默认全员接收）
   */
  private onCustomGroupNotify(data: any) {
    console.error("onCustomGroupNotify", data);
    // 作为卡片发送出去
  }


}
</script>

<style lang="stylus" scoped>
.fa-lgl
  bottom -3px!important

.redpacket-comp
  position fixed
  bottom 2000px
  transition all 0.01s 0.01s ease
  opacity 0
  &.show
    bottom 0
    opacity 1

</style>